"""
Copyright © 2020 Walkline Wang (https://walkline.wang)
Gitee: https://gitee.com/walkline/micropython-ble-library
Reference repo: https://github.com/micropython/micropython/tree/master/examples/bluetooth
"""
import struct
from bluetooth import UUID
from ble.const import BLEConst


PACK = struct.pack


class BLETools(object):
	@staticmethod
	def __decode_field(payload, adv_type):
		i = 0
		result = []

		if isinstance(payload, memoryview):
			payload = bytes(payload)

		while i + 1 < len(payload):
			if payload[i + 1] == adv_type:
				result.append(payload[i + 2:i + payload[i] + 1])
			i += 1 + payload[i]
		return result

	@staticmethod
	def decode_name(payload):
		n = BLETools.__decode_field(payload, BLEConst.ADType.COMPLETE_LOCAL_NAME)
		return str(n[0], 'utf-8') if n else ''

	@staticmethod
	def decode_services_data(payload):
		services = []
		data = []
		for u in BLETools.__decode_field(payload, BLEConst.ADType.SERVICE_DATA):
			services.append(UUID(u[:2]))
			data.append(u[2:])
		return services, data

	@staticmethod
	def decode_mac(addr):
		if isinstance(addr, memoryview):
			addr = bytes(addr)

		assert isinstance(addr, bytes) and len(addr) == 6, ValueError("mac address value error")
		return ":".join(['%02X' % byte for byte in addr])
